#!/usr/local/bin/perl -w
use strict;
use utf8;
use lib '../lib';

use Data::Dumper;
$Data::Dumper::Deparse = 1;

use NG::Sys::App 'NG::Sys::Loop::Daemon';
use NG::Ext::Cron;

my $app = new NG::Sys::App(logger => "daemon");
my $cron;

$app->run;

sub on_prepare_loop {
	my ($self) = @_;
	$cron = new NG::Ext::Cron(\&dispatcher);
	my $path = $app->{cfg}{path}{crontab};
	if(-e $path){
		$cron->load_crontab($path);
	}else{
		die "file not found ($path) for cron";
	}
	$cron->prepare_wait;
}
sub on_before_process {
	my($app) = @_;
	$cron->before_wait;
	return 1; # yes, do main process
}

sub on_process {
	my($app) = @_;
	$cron->wait_next;
}
sub dispatcher {
	my ($file,@args) = @_;
	$file =~ s/\s+$//;
	my $path = $app->{cfg}{path}{cron};
	$path .= "/".$file;
	$app->logger->info("Try exec cron($file)");
	if(-x $path){
		exec($path,@args);
	}elsif(-e $path){
		exec("perl",$path,@args);
	}else{
		die "No file cron($file)";
	}
	$app->logger->error("Cannot exec cron($file)");
}
